import _ from "@/assets/utils.js";
import { Button, Form, Input, Toast } from "antd-mobile";
import React, { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import NavBarAgain from "../components/NavBarAgain";
import api from "../store/api/index.js";
import { setUserInfoAsync } from "../store/slice/baseSlice";
import "./Login.less";
export default function Login(props) {
  let { navigate, usp } = props;
  const dispatch = useDispatch();

  // 定义状态
  const [disabled, setDisabled] = useState(false);
  const [sendText, setSendText] = useState("发送验证码");
  const [formIns] = Form.useForm();
  //1、 定义验证手机和验证码格式
  const validate = {
    phone(_, value) {
      value = value.trim();
      let reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (value.length === 0) {
        return Promise.reject(new Error("手机号不能能为空!"));
      }
      if (!reg.test(value)) {
        return Promise.reject(new Error("手机号格式有误!"));
      }
      return Promise.resolve();
    },
    code(_, value) {
      value = value.trim();
      let reg = /^\d{6}$/;
      if (value.length === 0) {
        return Promise.reject(new Error("验证码不能为空!"));
      }
      if (!reg.test(value)) {
        return Promise.reject(new Error("验证码格式有误！"));
      }
      return Promise.resolve();
    },
  };
  // 2、点击发送验证码，请求发送验证码，写入code.txt文件
  /* 发送验证码 */
  let timer = null,
    num = 31;
  const countdown = () => {
    num--;
    if (num === 0) {
      clearInterval(timer);
      timer = null;
      setSendText(`发送验证码`);
      setDisabled(false);
      return;
    }
    setSendText(`${num}秒后重发`);
  };
  const send = async () => {
    try {
      await formIns.validateFields(["phone"]);
      let phone = formIns.getFieldValue("phone");
      let { code } = await api.sendPhoneCode(phone);
      if (+code !== 0) {
        Toast.show({
          icon: "fail",
          content: "发送失败",
        });
        return;
      }
      // 发送成功
      setDisabled(true);
      countdown();
      if (!timer) timer = setInterval(countdown, 1000);
    } catch (_) {}
  };
  // 3、点击提交，验证手机和验证码格式，格式正确向服务器发送请求登录注册的请求。

  const submit = async () => {
    try {
      // +获取form的实例对phone和code进行验证
      await formIns.validateFields();
      // +获取phone和code作为参数请求登录
      let { phone, code } = formIns.getFieldsValue();
      let { code: codeHttp, token } = await api.login(phone, code);
      //   ++登录失败就提示，清空验证码
      if (+codeHttp !== 0) {
        Toast.show({
          icon: "fail",
          content: "登录失败",
        });
        formIns.resetFields(["code"]);
        return;
      }
      //   ++登录成功，1.储存对应的Token、2.储存登录者信息、3.提示、4.跳转。
      _.storage.set("tk", token);
      // 2.储存登录者信息
      dispatch(setUserInfoAsync());
      // 3.提示
      Toast.show({
        icon: "success",
        content: "登录/注册成功",
      });
      // 4.跳转
      let to = usp.get("to");
      to ? navigate(to, { replace: true }) : navigate(-1);
    } catch (_) {}
  };
  // 组件销毁的时候:把没有清除的定时器干掉
  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
    };
  }, []);
  return (
    <div className='login-box'>
      <NavBarAgain title={"登录/注册"} />
      <Form
        layout='horizontal'
        style={{ "--border-top": "none" }}
        footer={
          <Button block color='primary' size='large' onClick={submit}>
            提交
          </Button>
        }
        form={formIns}
        initialValues={{ phone: "", code: "" }}
      >
        <Form.Item
          name='phone'
          label='手机号'
          rules={[{ validator: validate.phone }]}
        >
          <Input placeholder='请输入手机号' />
        </Form.Item>
        <Form.Item
          name='code'
          label='验证码'
          rules={[{ validator: validate.code }]}
          extra={
            <Button
              size='small'
              color='primary'
              onClick={send}
              disabled={disabled}
            >
              {sendText}
            </Button>
          }
        >
          <Input placeholder='请输入验证码' />
        </Form.Item>
      </Form>
    </div>
  );
}
